package com.chat.config;

import DO.chat.ChatDO;
import com.chat.mapper.ChatMapper;
import constant.RedisPreKeyConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.utils.RankingUtils.getOriginalScore;
import static com.utils.RankingUtils.getSeconds;

@Component
public class DataLoader implements CommandLineRunner {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ChatMapper chatMapper;
  
    @Override  
    public void run(String... args) {
        // 1.1 查询数据库中的数据，查询 一天以内
        List<ChatDO> chatByDay = chatMapper.getChatByDay();

        // 1.2 查询数据库中的数据，查询 一周以内
        List<ChatDO> chatByWeek = chatMapper.getChatByWeek();

        // 1.3 查询数据库中的数据，查询 一天以内，一周以内，一个月以内的数据 set
        List<ChatDO> chatByMonth = chatMapper.getChatByMonth();


        // 2.1 初始化前先删除对应key
        redisTemplate.delete(RedisPreKeyConstant.RANKING_DAY);
        // 2.2 初始化前先删除对应key
        redisTemplate.delete(RedisPreKeyConstant.RANKING_WEEK);
        // 2.3 初始化前先删除对应key
        redisTemplate.delete(RedisPreKeyConstant.RANKING_MONTH);

        ZSetOperations<String, Object> zSetOperationsDay = redisTemplate.opsForZSet();
        ZSetOperations<String, Object> zSetOperationsWeek = redisTemplate.opsForZSet();
        ZSetOperations<String, Object> zSetOperationsMonth = redisTemplate.opsForZSet();


        // 3.1 day
        for (ChatDO chatDO : chatByDay) {
            // key 命名方式： 帖子id，+ _ + 自1970以来的秒数
            zSetOperationsDay.add(RedisPreKeyConstant.RANKING_DAY,getSeconds(chatDO.getCreatedTime()) + "_" + chatDO.getId(),getOriginalScore(chatDO.getCollectionNumber(),chatDO.getLikeNumber(),chatDO.getCommentsNumber()));
        }

        // 3.2 week
        for (ChatDO chatDO : chatByWeek) {
            // key 命名方式： 帖子id，+ _ + 自1970以来的秒数
            zSetOperationsWeek.add(RedisPreKeyConstant.RANKING_WEEK,getSeconds(chatDO.getCreatedTime()) + "_" + chatDO.getId(),getOriginalScore(chatDO.getCollectionNumber(),chatDO.getLikeNumber(),chatDO.getCommentsNumber()));
        }


        // 3.3 month
        for (ChatDO chatDO : chatByMonth) {
            // key 命名方式： 帖子id，+ _ + 自1970以来的秒数
            zSetOperationsMonth.add(RedisPreKeyConstant.RANKING_MONTH,getSeconds(chatDO.getCreatedTime()) + "_" + chatDO.getId(),getOriginalScore(chatDO.getCollectionNumber(),chatDO.getLikeNumber(),chatDO.getCommentsNumber()));
        }

    }
}